﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mailer.Model.Types;
using NHibernate;
using NHibernate.Criterion;

namespace Mailer.Model.Repositories
{
	public class ApplicationRepository
	{
		public static List<Application> GetApplicationsForUser(Guid userid)
		{
			List<Application> ret = new List<Application>();

			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				User user = sess.Get<User>(userid);
				if (user != null)
				{
					foreach (Application a in user.Applications)
						ret.Add(a);
				}
				SessionUtilities.EndSession(sess);
			}

			return ret;
		}


		public static Application Get(Guid appid)
		{
			Application ret = null;


			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				ret = sess.Get<Application>(appid);
				SessionUtilities.EndSession(sess);
			}

			return ret;
		}


		public static Application GetByPublicID(string publicid)
		{
			Application ret = null;


			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				ret = sess.CreateCriteria<Application>()
					.Add(Expression.Eq("PublicID", publicid))
					.UniqueResult<Application>();

				SessionUtilities.EndSession(sess);
			}

			return ret;
		}

		public static Application GetByPublicID(string publicid, string secret)
		{
			Application ret = null;


			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				ret = sess.CreateCriteria<Application>()
					.Add(Expression.Eq("PublicID", publicid))
					.Add(Expression.Eq("Secret", secret))
					.UniqueResult<Application>();

				SessionUtilities.EndSession(sess);
			}

			return ret;
		}

	}
}
